package com.molin.mapTest.TreeMapTest;

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class Demo1 {
    public static void main(String[] args) {
        //按照学生年龄进行排序,从大到小排
        TreeMap<Student, String> studentStringTreeMap = getStudentStringTreeMap1();
        //按照学生年龄进行排序,从小到大排
//        TreeMap<Student, String> studentStringTreeMap = getStudentStringTreeMap();
        studentStringTreeMap.put(new Student("xiaohei", 23), "pukou");
        studentStringTreeMap.put(new Student("dapang", 25), "jianye");
        studentStringTreeMap.put(new Student("xiaomei", 20), "gulou");
        studentStringTreeMap.put(new Student("xiaomi", 25), "gulou");
        System.out.println("方式1=========================");
        studentStringTreeMap.forEach(
                (Student key, String value) -> {
                    System.out.println(key + "-----" + value);
                }
        );
        System.out.println("方式2=========================");
        Set<Map.Entry<Student, String>> entries = studentStringTreeMap.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey() + "-----" + entry.getValue());
        }

    }

    public static TreeMap<Student, String> getStudentStringTreeMap() {
//        比较器排序实现Comparator
        return new TreeMap<>(new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    int result=o1.getAge()-o2.getAge();
                    result=result==0?o1.getName().compareTo(o2.getName()):result;
                    return result;
                }
            });
    }

    public static TreeMap<Student, String> getStudentStringTreeMap1() {
        TreeMap<Student, String> studentStringTreeMap = new TreeMap<>();

        return studentStringTreeMap;
    }
}

//自然排序，实现Comarable<T> 接口
class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        int result = o.age - this.age;
        result = result == 0 ? this.name.compareTo(o.name) : result;
        return result;
    }
}